import json

import flask
from elasticsearch import NotFoundError
from flask import request
import threading
import interface
import time


service_instance_lock = threading.Lock()
clu_result_lock = threading.Lock()
server = flask.Flask(__name__,template_folder='./static/templates')  # 实例化server，把当前这个python文件当作一个服务，__name__代表当前这个python文件


@server.route('/api/clu', methods=['get'], )
def clu():
    # res = {'msg':'这是我开发的第一个接口','msg_code':'0000'}
    # return json.dumps(res,ensure_ascii=False)
    # json.dumps 序列化时对中文默认使用的ascii编码.想输出真正的中文需要指定ensure_ascii=False

    # clu_result_lock.acquire()
    # with open(r'clu.txt', 'r', encoding='utf-8') as file_open:
    #     data = json.load(file_open)
    # data = interface.clustering(3)
    # clu_result_lock.release()
    data = interface.clustering(3)
    return data

@server.route('/api/lstm',methods=['get'],)  # 'index'是接口路径，如methods不写，则默认get请求
def lstm():
    # res = {'msg':'这是我开发的第一个接口','msg_code':'0000'}
    # return json.dumps(res,ensure_ascii=False)
    # json.dumps 序列化时对中文默认使用的ascii编码.想输出真正的中文需要指定ensure_ascii=False
    service = request.values.get('service')
    instance = request.values.get('instance')
    # print(server, instance)
    #interface.LSTM_train(service, instance)
    data = interface.LSTM_forecast(service, instance)
    return data

@server.route('/api/lstm/train',methods=['get'],)  # 'index'是接口路径，如methods不写，则默认get请求
def lstm():
    # res = {'msg':'这是我开发的第一个接口','msg_code':'0000'}
    # return json.dumps(res,ensure_ascii=False)
    # json.dumps 序列化时对中文默认使用的ascii编码.想输出真正的中文需要指定ensure_ascii=False
    service = request.values.get('service')
    instance = request.values.get('instance')
    # print(server, instance)
    interface.LSTM_train(service, instance)
    #data = interface.LSTM_forecast(service, instance)
    return "训练成功"

@server.route('/api/instance',methods=['get'],)  # 'index'是接口路径，如methods不写，则默认get请求
def getInstance():

    serviceName = request.values.get('service')
    # service_instance_lock.acquire()
    # data = None
    # with open(r'service.txt', 'r', encoding='utf-8') as file_open:
    #     data = json.load(file_open)
    # service_instance_lock.release()

    mapping = interface.get_service_instance_info()
    instance = mapping.get(serviceName)
    if not instance:
        instance = []
    return json.dumps(instance)


@server.route('/api/getservice',methods=['get'],)  # 'index'是接口路径，如methods不写，则默认get请求
def getService():

    data = ""
    # service_instance_lock.acquire()
    # with open(r'service.txt', 'r', encoding='utf-8') as file_open:
    #     data = json.load(file_open)
    # service_instance_lock.release()
    # print(type(data))
    # return str(list(data.keys()))
    mapping = interface.get_service_instance_info()
    return json.dumps(list(mapping.keys()))
def service_instance_thread():

    print("获取服务名中")
    while True:
        print("获取")
        try:
            service_info = interface.get_service_instance_info()
            service_info = json.dumps(service_info, ensure_ascii=False)
        except NotFoundError as nfe:
            print("service_instance_thread", nfe)
            print("10s后重新获取数据")
            time.sleep(10)
            continue
        service_instance_lock.acquire()
        with open(r'./service.txt', mode='w', encoding='utf-8') as tf2:
            tf2.write(service_info)
        service_instance_lock.release()
        print(service_info)


def clu_result():
    print("聚类结果")
    while True:
        print("获取")
        try:
            result = interface.clustering(3)
        except NotFoundError as nfe:
            print("clu_result", nfe)
            print("10s后重新获取数据")
            time.sleep(10)
            continue
        result = json.dumps(result, ensure_ascii=False, indent=4)
        clu_result_lock.acquire()
        with open(r'./clu.txt', mode='w', encoding='utf8') as tf2:
            tf2.write(result)
        clu_result_lock.release()
        print(result)


def train():
    print("训练")
    while True:
        print("开始训练")
        mapping = interface.get_service_instance_info()
        for service in mapping.keys():
            print("train: "+ service)
            interface.LSTM_train(service, None)
            for instance in mapping.get(service):
                print("train: " + service +" ----- " + instance);
                interface.LSTM_train(service, instance)
        time.sleep(3600)


if __name__ == "__main__":
    # threading.Thread(target=service_instance_thread, name="service_instance_thread").start()
    # threading.Thread(target=clu_result, name="clu_result").start()
    threading.Thread(target=train, name="train").start()
    server.config['JSON_AS_ASCII'] = False
    server.run(port=8888, debug=True, host='0.0.0.0')
